//
//  LYSettingViewController.swift
//  LYOnlineBanking
//
//  Created by 李永彬 on 2025/7/27.
//

import UIKit

class LYSettingViewController: LYBaseViewController {
    private lazy var iconImgView: UIImageView = {
        let iv = UIImageView()
        iv.contentMode = .scaleAspectFit
        iv.clipsToBounds = true
        iv.image = UIImage(named: "setting_logo")
        return iv
    }()
    
    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.italicSystemFont(ofSize: 28)
        label.textColor = UIColor(hex: "#FFFFFF")
        label.textAlignment = .center
        label.text = LYlocalizedString("Tunai Pasti") 
        return label
    }()
    
    lazy var gooutButton: UIButton = {
        let button = UIButton(type: .custom)
        button.addTarget(self, action: #selector(goOutButtonAction(_:)), for: .touchUpInside)
        button.setTitleColor(UIColor(hex: "#000000"), for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .semibold)
        button.setTitle(LYlocalizedString("Go Out"), for: .normal)
        button.backgroundColor = UIColor(hex: "#FFFFFF")
        button.layer.masksToBounds = true
        button.layer.cornerRadius = 8.0
        return button
    }()
    
    lazy var cancellationButton: UIButton = {
        let button = UIButton(type: .custom)
        button.addTarget(self, action: #selector(cancelButtonAction(_:)), for: .touchUpInside)
        button.setTitleColor(UIColor(hex: "#D56500"), for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .semibold)
        button.setTitle(LYlocalizedString("Account cancellation"), for: .normal)
        button.backgroundColor = UIColor(hex: "#FFB26C")
        button.layer.masksToBounds = true
        button.layer.cornerRadius = 8.0
        return button
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.title = LYlocalizedString("setup")
    
        self.view.addSubview(iconImgView)
        self.view.addSubview(titleLabel)
        self.view.addSubview(gooutButton)
        self.view.addSubview(cancellationButton)
        if appCountryEnv == .indonesia {
            cancellationButton.isHidden = true
        } else {
            cancellationButton.isHidden = false
        }
        iconImgView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top).offset(40)
            make.width.height.equalTo(144)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.centerX.equalTo(iconImgView)
            make.top.equalTo(iconImgView.snp.bottom).offset(10)
        }
        
        gooutButton.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(50)
            make.leading.trailing.equalToSuperview().inset(14)
            make.height.equalTo(51)
        }
        
        cancellationButton.snp.makeConstraints { make in
            make.top.equalTo(gooutButton.snp.bottom).offset(10)
            make.leading.trailing.equalTo(gooutButton)
            make.height.equalTo(51)
        }
    }
    
    @objc func goOutButtonAction(_ sender: UIButton) {
        showGoOutAlertView()
    }

    @objc func cancelButtonAction(_ sender: UIButton) {
        showAccountCancellationPravicyAlertView()
    }
    
    func showGoOutAlertView() {
        
        let alert = LYCustomAlertView(
            title: LYlocalizedString("Go Out"),
            message: LYlocalizedString("go_out_content")
        )
        
        let goOutBtn = LYCustomAlertViewAction.getButton(with: LYlocalizedString("Go Out"),
                                                         actionType: .unObvious)
        
        let cancelBtn = LYCustomAlertViewAction.getButton(with: LYlocalizedString("Cancel"),
                                                         actionType: .obvious)
        // 添加按钮到弹窗
        alert.addButton(goOutBtn) {
            alert.hide {
                LYHUDUtils.showLoading()
                LYStocksManager.fetchLoginOut { success, msg, error in
                    if error == nil {
                        NotificationCenter.default.post(name: .logOutNotificationKey, object: nil)
                        NotificationCenter.default.post(name: .NotLoginInNotificationKey, object: nil)
                        LYHUDUtils.hideHUD()
                    } else {
                        
                        LYHUDUtils.showToast(msg)
                    }
                }
            }
        }
        
        alert.addButton(cancelBtn) {
            alert.hide()
        }
        
        // 显示弹窗
        alert.show()
    }
    
    func showAccountCancellationAlertView() {
        
        // 开始监控网络权限状态
        NetworkPermissionManager.shared.startMonitoring()
        guard NetworkPermissionManager.shared.isNetworkPermissionGranted else {
            NetworkPermissionManager.shared.stopMonitoring()
            showNoNetworkPermissionAlertView()
            return
        }
        NetworkPermissionManager.shared.stopMonitoring()

        let alert = LYCustomAlertView(
            title: LYlocalizedString("Title"),
            message: LYlocalizedString("sure account cancellation")
        )
        
        let cancelBtn = LYCustomAlertViewAction.getButton(with: LYlocalizedString("Cancel"),
                                                         actionType: .unObvious)
        
        let okBtn = LYCustomAlertViewAction.getButton(with: LYlocalizedString("OK"),
                                                         actionType: .obvious)
        // 添加按钮到弹窗
        alert.addButton(cancelBtn) {
            alert.hide()
        }
        
        alert.addButton(okBtn) {
            
            alert.hide {
                LYHUDUtils.showLoading()
                LYStocksManager.fetchAccountCancellation { success, msg, error in
                    if error == nil {
                        NotificationCenter.default.post(name: .logOutNotificationKey, object: nil)
                        NotificationCenter.default.post(name: .NotLoginInNotificationKey, object: nil)
                        LYHUDUtils.hideHUD()
                    } else {
                        LYHUDUtils.showToast(msg)
                    }
                }
            }
        }
        
        // 显示弹窗
        alert.show()
    }
    
    func showNoNetworkPermissionAlertView() {
        
        let alert = LYCustomAlertView(
            title: LYlocalizedString(""),
            message: LYlocalizedString("No network available at the moment")
        )
        
        let stopBtn = LYCustomAlertViewAction.getButton(with: LYlocalizedString("Stop"),
                                                         actionType: .unObvious)
        
        let turningOnBtn = LYCustomAlertViewAction.getButton(with: LYlocalizedString("Turning on"),
                                                         actionType: .obvious)
        // 添加按钮到弹窗
        alert.addButton(stopBtn) {
            alert.hide()
        }
        
        alert.addButton(turningOnBtn) {
            alert.hide { [weak self] in
                guard let self = self else { return }
                self.openAppSettings()
            }
        }
        
        // 显示弹窗
        alert.show()
    }
    
    func openAppSettings() {
        guard let settingsUrl = URL(string: UIApplication.openSettingsURLString),
              UIApplication.shared.canOpenURL(settingsUrl) else {
            return
        }
        
        UIApplication.shared.open(settingsUrl, options: [:], completionHandler: nil)
    }
    
    func showAccountCancellationPravicyAlertView() {
        let baseView = LYSettingAccountCancelAlertView()
        let alert = LYCustomAlertView(view: baseView,
                                      backgroundImage: UIImage(named: "account_cancel_bg"))
       
        baseView.deleteActionClosure = { [weak self] isSelected in
            guard let self = self else { return }
            if isSelected {
                alert.hide {[weak self] in
                    guard let self = self else { return }
                    self.showAccountCancellationAlertView()
                }
            } else {
                LYHUDUtils.showToast(LYlocalizedString("Please agree to the Privacy Policy"))
            }
        }
        
        baseView.cancelActionClosure = {
            alert.hide()
        }

        // 显示弹窗
        alert.show()
    }
}

